<template>
  <el-card>
    <el-form label-width="80px">
      <el-form-item label="SPU名称">
        <span>{{ spuName }}</span>
      </el-form-item>
      <el-form-item label="SKU名称">
        <el-input v-model="skuInfo.skuName" placeholder="请输入SKU名称" />
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number v-model="skuInfo.price" style="width: 100%" controls-position="right" :min="0" @change="handleChange" />
      </el-form-item>
      <el-form-item label="重量">
        <el-input-number v-model="skuInfo.weight" style="width: 100%" controls-position="right" :min="0" @change="handleChange" />
      </el-form-item>
      <el-form-item label="SKU描述">
        <el-input v-model="skuInfo.skuDesc" type="textarea" placeholder="请输入SKU描述" />
      </el-form-item>
      <el-form-item label="平台属性">
        <el-row>
          <el-col v-for="(attr, index) in attrList" :key="attr.id" :md="8" :sm="12" :xs="24" class="el-sku-col">
            <el-form-item :label="attr.attrName">
              <el-select v-model="skuInfo.skuAttrValueList[index]">
                <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.attrId" :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`">{{ attrValue.valueName }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="销售属性">
        <el-row>
          <el-col v-for="spuSaleAttr in spuSaleAttrList" :key="spuSaleAttr.id" :md="8" :sm="12" :xs="24" class="el-sku-col">
            <el-form-item :label="spuSaleAttr.saleAttrName">
              <el-select>
                <el-option v-for="saleAttr in spuSaleAttr.spuSaleAttrValueList" :key="saleAttr.id" :value="`${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${saleAttr.id}:${saleAttr.saleAttrValueName}`">{{ saleAttr.saleAttrValueName }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="SKU属性">
        <el-table ref="multipleTable" border tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="图片" align="center">
            <template v-slot="{row}">
              <img :src="row.imgUrl" :alt="row.imgName" style="width:150px;height:150px;">
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" />
          <el-table-column label="操作" show-overflow-tooltip align="center">
            <template v-slot="{ row }">
              <el-button v-if="row.isDefault === '0'" type="primary" @click="setDefault(row)">设置默认图片</el-button>
              <el-button v-else type="success" disabled>默认图片</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { mapState } from 'vuex'
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from '@/api/product/spu'
import { reqGetAttrList } from '@/api/product/attr'
import { reqSaveSkuInfo } from '@/api/product/sku'

export default {
  name: 'SaveSpu',
  data() {
    const skuImageListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请至少选择一条图片')
        return
      }
      callback()
    }
    const skuAttrValueListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择一个平台属性')
        return
      }
      callback()
    }
    const skuSaleAttrValueListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择一个销售属性')
        return
      }
      callback()
    }
    return {
      num: 0,
      spuImageList: [], // 图片列表
      spuSaleAttrList: [], // 销售属性及详细属性值列表
      attrList: [], // 平台属性列表
      skuInfo: {
        // spu名称
        skuName: '',
        // 价格
        price: 0,
        // 重量
        weight: 0,
        // 描述
        skuDesc: '',
        // 默认图片
        skuDefaultImg: '',
        // 平台属性
        skuAttrValueList: [],
        // 图片列表
        skuImageList: [],
        // 销售属性列表
        skuSaleAttrValueList: []
      },
      rules: {
        skuName: [{ required: true, message: '请输入SKU名称', trigger: 'blur' }],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
        skuDesc: [{ required: true, message: '请输入sku描述', trigger: 'blur' }],
        skuImageList: [
          {
            required: true,
            validator: skuImageListValidate,
            trigger: 'change'
          }
        ],
        skuAttrValueList: [
          {
            required: true,
            validator: skuAttrValueListValidate,
            trigger: 'change'
          }
        ],
        skuSaleAttrValueList: [
          {
            required: true,
            validator: skuSaleAttrValueListValidate,
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id']),
    ...mapState('spu', ['spuId'])
  },
  async mounted() {
    const { category1Id, category2Id, category3Id } = this
    const [responseAttList, responseSpuSaleAttrList, responseSpuImageList] = await Promise.allSettled([reqGetAttrList({ category1Id, category2Id, category3Id }), reqGetSpuSaleAttrList(this.spuId), reqGetSpuImageList(this.spuId)])
    console.log(responseAttList)
    if (responseSpuImageList.status === 'fulfilled') {
      this.spuImageList = responseSpuImageList.value.data.map(item => {
        return {
          ...item,
          isDefault: 0
        }
      })
      if (responseSpuSaleAttrList.status === 'fulfilled') {
        this.spuSaleAttrList = responseSpuSaleAttrList.value.data
      }
    }
  },
  methods: {
    // 1. 设置默认图片
    setDefault(row) {
      this.spuImageList.forEach(item => {
        item.isDefault = '0'
      })
      row.isDefault = '1'
    },
    // 2. 收集所选的图片
    handleSelectionChange(val) {
      // console.log(val);
      this.skuInfo.spuImageList = val
    },
    sumbitForm() {
      this.$refs.skuForm.validate(async valid => {
        if (valid) {
          if (!this.skuInfo.skuDefaultImg) {
            this.$messages.error('请选择默认图片')
            return
          }
          const { spuId, category3Id } = this
          const { skuName, price, skuDesc, weigth, skuDefaultImg, skuImageList, skuAttrValueList, skuSaleAttrValueList } = this.skuInfo
          const result = await reqSaveSkuInfo({
            spuId,
            category3Id,
            skuName,
            price,
            weigth,
            skuDesc,
            skuDefaultImg,
            skuImageList,
            skuAttrValueList: skuAttrValueList.filter(Boolean).map(item => {
              const [attrId, attrName, valueId, valueName] = item.split(':')
              return {
                attrId,
                attrName,
                valueId,
                valueName
              }
            }),
            skuSaleAttrValueList: skuSaleAttrValueList.filter(Boolean).map(item => {
              const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(':')
              return {
                saleAttrId,
                saleAttrName,
                saleAttrValueId,
                saleAttrValueName
              }
            })
          })
          if (result.code === 200) {
            this.$message.success('添加SKU对象成功')
            this.$emit('update:visible', 1)
          } else {
            this.$message.error('添加SKU对象失败')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleChange(value) {
      console.log(value)
    }
  }
}
</script>

<style scoped>
</style>
